package com.yanhao.act.fragment.home

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.yanhao.act.WebInfoActivity
import com.yanhao.adapter.ArticleListAdapter
import com.yanhao.adapter.MainBannerAdapter
import com.yanhao.bean.ApiResult
import com.yanhao.bean.BannerData
import com.yanhao.databinding.FragmentHomeBinding
import com.yanhao.viewmode.HomeFgViewModel
import com.yanhao.viewmode.HomeFgViewModelFactory
import com.youth.banner.indicator.CircleIndicator
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
class HomeFragment : Fragment() {

    companion object {
        val FG_TAG = "SearchFragment"
    }

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    private var mDataBanner: MutableList<BannerData> = mutableListOf()

    private var bannerAdapter: MainBannerAdapter? = null

    //TODO 1
//    private var mDataArticle: MutableList<Article> = mutableListOf()
    //    private var articleAdapter: ArticleAdapter? = null
    //TODO 2
    private val articleListAdapter by lazy {
        ArticleListAdapter()
    }
    private val viewmodel by viewModels<HomeFgViewModel> {
        HomeFgViewModelFactory()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        //获取banner数据
        viewmodel.getBanner()
        //获取文章数据
        viewmodel.getHomeAndTopArticels()
        initObserve()
        initEvent()
    }

    private fun initView() {
        binding.btnTest.setOnClickListener {
            viewmodel.plus()
        }
        lifecycleScope.launch {
            viewmodel.count.collect {
                binding.btnTest.text = "$it"
            }
        }
        binding.refreshLayout.setEnableRefresh(true)//启用下拉刷新
        binding.refreshLayout.setEnableLoadMore(true)//启用加载更多
        binding.refreshLayout.setEnableOverScrollBounce(true)

        //TODO 2
        binding.recyclerview.layoutManager = LinearLayoutManager(requireActivity())
        binding.recyclerview.adapter = articleListAdapter

        bannerAdapter = MainBannerAdapter(requireActivity(), mDataBanner)
        binding.bannerTop?.let {
            it.addBannerLifecycleObserver(requireActivity())
            it.setAdapter(bannerAdapter)
            it.setIndicator(CircleIndicator(requireActivity()))
        }

        //TODO 1
//        articleAdapter = ArticleAdapter(mDataArticle)
//        articleAdapter?.apply {
//            setOnItemClickListener { i, view ->
//                Toast.makeText(requireContext(), "点击了 ${mDataArticle[i].title}", Toast.LENGTH_SHORT)
//                    .show()
//            }
//            setonItemChildClickListener { i, view ->
//                Toast.makeText(
//                    requireContext(),
//                    "点击了 ${mDataArticle[i].title} 的收藏",
//                    Toast.LENGTH_SHORT
//                )
//                    .show()
//            }
//        }
//        binding.recyclerview.apply {
//            layoutManager = LinearLayoutManager(requireActivity())
//            adapter = articleAdapter
//        }
        //TODO 2
        articleListAdapter.apply {

            setOnItemClickListener { i, _ ->
                val data = this@HomeFragment.articleListAdapter.currentList[i]
                val intent = Intent(requireContext(), WebInfoActivity::class.java).apply {
                    putExtra(WebInfoActivity.LINK, data.link)
                    putExtra(WebInfoActivity.TITLE, data.title)
                }
                startActivity(intent)
            }

            setonItemChildClickListener { i, _ ->
                viewmodel.collectArticle(this@HomeFragment.articleListAdapter.currentList[i].id)
            }
        }

    }

    private fun initObserve() {
//        viewmodel.homeArticles.observe(viewLifecycleOwner) {
//            //TODO 1
////            mDataArticle.clear()
////            it?.let {
////                mDataArticle.addAll(it)
////            }
////            articleAdapter?.let {
////                it.notifyDataSetChanged()
////            }
//            //TODO 2
//            articleListAdapter.submitList(it)
//
//            binding.refreshLayout.finishRefresh(0)
//            binding.refreshLayout.finishLoadMore(0)
//        }

//        viewmodel.bannerData.observe(viewLifecycleOwner) {
//            mDataBanner.clear()
//            mDataBanner.addAll(it)
//            bannerAdapter?.notifyDataSetChanged()
//        }

//        viewmodel.bannerData.observe(viewLifecycleOwner) {
//            when (it) {
//                is ApiResult.Loadding -> {
//                    Log.e("TAG", "开始加载loadding: ")
//                }
//                is ApiResult.Success -> {
//                    val data = it.data
//                    mDataBanner.clear()
//                    mDataBanner.addAll(data)
//                    bannerAdapter?.notifyDataSetChanged()
//                }
//                is ApiResult.Faiure -> {
//                    Toast.makeText(requireContext(), "banner错误:${it.errorMsg}", Toast.LENGTH_SHORT)
//                        .show()
//                }
//                is ApiResult.Completion -> {
//                    Log.e("TAG", "加载loadding结束: ")
//                }
//            }
//
//        }

        viewmodel.bannerData.observe(viewLifecycleOwner) {
            when (it.state) {
                is ApiResult.Loadding -> {
                    Log.e("TAG", "开始加载loadding: ")
                }
                is ApiResult.Success -> {
                    val data = it.state.data
                    mDataBanner.clear()
                    mDataBanner.addAll(data)
                    bannerAdapter?.notifyDataSetChanged()
                }
                is ApiResult.Faiure -> {
                    Toast.makeText(requireContext(), "banner错误:${it.state.errorMsg}", Toast.LENGTH_SHORT)
                        .show()
                }
                is ApiResult.Completion -> {
                    Log.e("TAG", "加载loadding结束: ")
                }
            }

        }

//        lifecycleScope.launch {
//            viewmodel.bannerData.collect {
//                mDataBanner.clear()
//                mDataBanner.addAll(it)
//                bannerAdapter?.notifyDataSetChanged()
//            }
//        }
//
        viewmodel.homeArticles.observe(viewLifecycleOwner) {
            //TODO 1
//            mDataArticle.clear()
//            it?.let {
//                mDataArticle.addAll(it)
//            }
//            articleAdapter?.let {
//                it.notifyDataSetChanged()
//            }
            //TODO 2
            articleListAdapter.submitList(it)

            binding.refreshLayout.finishRefresh(0)
            binding.refreshLayout.finishLoadMore(0)
        }

//        viewmodel.bannerErrMsg.observe(viewLifecycleOwner) {
//            Toast.makeText(requireContext(), it, Toast.LENGTH_SHORT).show()
//        }
        viewmodel.errorMsg.observe(viewLifecycleOwner) {
            Toast.makeText(requireContext(), it, Toast.LENGTH_SHORT).show()
        }
    }

    private fun initEvent() {
        binding.cvSearch.setOnClickListener {
            val intent = Intent(requireContext(), ActivitySearch::class.java)
            startActivity(intent)
        }


        binding.refreshLayout.setOnRefreshListener {
            viewmodel.refreshCurrent()
        }

        binding.refreshLayout.setOnLoadMoreListener {
            viewmodel.onLoadMoreCurrent()
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }


}